package util

import (
	"log"

	consul_api "github.com/hashicorp/consul/api"
)

var consulClient *consul_api.Client

func init() {
	config := consul_api.DefaultConfig()
	config.Address = "192.168.56.1:8500"

	//服务注册
	client, err := consul_api.NewClient(config)
	if err != nil {
		log.Fatal(err)
	}

	consulClient = client
}

//服务注册
func RegService() {

	//创建服务注册信息
	reg := consul_api.AgentServiceRegistration{}
	reg.ID = "userservice"
	reg.Name = "userservice"
	reg.Address = "192.168.56.1"
	reg.Port = 8081
	reg.Tags = []string{"primary"}

	check := consul_api.AgentServiceCheck{}
	check.Interval = "5s"
	check.HTTP = "http://192.168.56.1:8081/health"
	reg.Check = &check

	//服务注册
	err :=consulClient.Agent().ServiceRegister(&reg)
	if err != nil {
		log.Fatal(err)
	}
}

func Unregservice() {
	consulClient.Agent().ServiceDeregister("userservice")
}
